import { kebabCase, pick, camelCase, isPlainObject } from 'lodash'
import attributes from '@/views/edit/config/attributes'

export function obj2AttrString (obj) {
  return Object.keys(obj)
    .reduce((total, key) => {
      if (!obj[key]) return total
      if (key === 'v-model') {
        return `${total} v-model="${obj[key]}"`
      }
      if (isPlainObject(obj[key])) {
        return `${total} ${key}='${JSON.stringify(obj[key])}'`
      }
      return `${total} ${key}="${obj[key]}"`
    }, '')
}

export function formatObjectKey (obj) {
  return Object.keys(obj)
    .reduce((total, key) => ({
      ...total,
      [kebabCase(key)]: obj[key]
    }), {})
}

export function obj2AttrStringByAttributes (conf, Attributes) {
  return obj2AttrString(pick(formatObjectKey(conf), Attributes))
}

export function attrValAddPx (obj, keys) {
  if (!Array.isArray(keys)) keys = [keys]
  return Object.keys(obj)
    .reduce((total, key) => {
      return keys.includes(key)
        ? {
          ...total,
          [key]: obj[key] + 'px'
        }
        : {
          ...total,
          [key]: obj[key]
        }
    }, {})
}

export function buildTag ({ tag, conf, children = '', addPxAttrs }) {
  return `<${tag} ${obj2AttrStringByAttributes(
    attrValAddPx(conf, addPxAttrs),
    attributes[`${camelCase(tag)}Attributes`]
  )}>${children}</${tag}>`
}

function buildElFormItem ({ componentsConf, formConf }) {
  let template = ''
  componentsConf.forEach((conf, index) => {
    template += buildTag({
      tag: 'el-form-item',
      conf: { ...conf, ...formConf },
      addPxAttrs: 'labelWidth',
      children: buildTag({
        tag: conf.tag,
        conf
      })
    })
  })
  return template
}

export default function generateVueTemplate (conf) {
  const elFormAttrsStr = obj2AttrStringByAttributes(attrValAddPx(conf.formConf, 'labelWidth'), attributes.elFormAttributes)
  const tempFile = `
<template>
<el-form ${elFormAttrsStr} >
  ${buildElFormItem(conf)}
  <el-form-item>
    <el-button type="primary" @click="onSubmit">立即创建</el-button>
    <el-button>取消</el-button>
  </el-form-item>
</el-form>
</template>
  `
  return tempFile
}
